import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Class converts files from native encoding to utf-8
 * 
 * @author 6310
 * 
 */
public class ToUTF8 {

	/**
	 * Usage: [-dir <path/to/files>] <source_extension> <output_extension>
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		String dir = null;
		String srcExt = null;
		String outExt = null;

		if (args.length == 4 && args[0] != null
				&& args[0].equalsIgnoreCase("-dir")) {
			dir = args[1];
			srcExt = args[2];
			outExt = args[3];
		} else if (args.length == 2) {
			dir = ".";
			srcExt = args[0];
			outExt = args[1];
		} else {
			printHelp();
			return;
		}

		convert(dir, srcExt, outExt);

	}

	private static void convert(String directory, String sourceExtension,
			String outputExtension) {
		printMsg("Entered to \""+directory+"\"");
		if (directory == null || sourceExtension == null
				|| outputExtension == null) {
			printMsg("SEVERE: Illegal parameters: dir=" + directory
					+ ", source_extension=" + sourceExtension
					+ ", output extension=" + outputExtension);
			return;
		}
		File dir = new File(directory);
		if (!dir.exists()) {
			printMsg("SEVERE: Directory " + dir.getAbsolutePath()
					+ " doesn't exist");
		}

		FileFilter filter = new FileFilterImpl(sourceExtension);
		File[] files = dir.listFiles(filter);

		if (files == null || files.length == 0) {
			printMsg("INFO: Haven't found any source files");
			return;
		}

		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			if (file.isDirectory()){
				convert(file.getAbsolutePath(), sourceExtension, outputExtension);
				continue;
			}
			performCommand(file, sourceExtension, outputExtension);
		}
	}

	private static void performCommand(File file, String sourceExtension,
			String outputExtension) {
		String s = null;
		try {
			String spath = file.getPath();
			String opath = spath.substring(0, spath.length()
					- sourceExtension.length())
					+ outputExtension;
			String java_home = System.getenv("java_home");
			Process p = Runtime.getRuntime().exec(
					"\"" + java_home + "\\bin\\native2ascii\" -encoding utf-8 "
							+ spath + " " + opath);

			BufferedReader stdInput = new BufferedReader(new InputStreamReader(
					p.getInputStream()));

			BufferedReader stdError = new BufferedReader(new InputStreamReader(
					p.getErrorStream()));

			// read the output from the command

			// Here is the standard output of the command
			while ((s = stdInput.readLine()) != null) {
				System.out.println(s);
			}

			// read any errors from the attempted command

			// Here is the standard error of the command (if any)
			while ((s = stdError.readLine()) != null) {
				System.out.println(s);
			}

		} catch (IOException e) {
			System.out.println("Exception happened: ");
			e.printStackTrace();
			System.exit(-1);
		}

	}

	static class FileFilterImpl implements FileFilter {
		public String ext = null;

		public FileFilterImpl(String ext) {
			this.ext = "." + ext.toLowerCase();
		}

		public boolean accept(File pathname) {
			// TODO Auto-generated method stub
			return pathname.getName().toLowerCase().endsWith(ext)
					|| pathname.isDirectory();
		}

	}

	private static void printMsg(String msg) {
		System.out.println(msg);
	}

	private static void printHelp() {
		printMsg("Usage: [-dir <path/to/files>] <source_extension> <output_extension>");

	}

}
